package com.cai.kcsj.controller.pre;

import com.cai.kcsj.entity.Comtent;
import com.cai.kcsj.entity.Goods;
import com.cai.kcsj.entity.Order;
import com.cai.kcsj.entity.User;
import com.cai.kcsj.service.ComtentServer;
import com.cai.kcsj.service.GoodsServer;
import com.cai.kcsj.service.OrderServer;
import com.cai.kcsj.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @version 1.0
 * @author：蔡松坡
 * @date：2021/1/5 11 : 35
 * @package：com.cai.kcsj.controller
 */
@Controller
@RequestMapping("/preindex")
public class PreIndexController {
    @Autowired
    private GoodsServer goodsServer;

    @Autowired
    private OrderServer orderServer;

    @Autowired
    private ComtentServer comtentServer;

    @RequestMapping("/preindex")
    public String index(Model model,@RequestParam(defaultValue = "1") Integer current){
        int startpage = (current-1)*5;
        int count = goodsServer.getGoodsCount();
        int page = count%5==0?count/5:count/5+1;
        List<Goods> goods = goodsServer.selectGoodsList(startpage);
        model.addAttribute("goodsList",goods);
        model.addAttribute("page",page);
        model.addAttribute("current",current);
        return "prezs";
    }

    @RequestMapping("/onlygoods/{id}")
    public String onlygoods(HttpServletRequest request,Model model,@PathVariable("id") Integer id){
        //User user = (User) request.getSession().getAttribute("user");
        //Integer uid = user.getId();
        Goods goods = goodsServer.selectGoodsById(id);
        List<Comtent> comtents = comtentServer.selectComById(id);
        model.addAttribute("goods",goods);
        model.addAttribute("comtentsList",comtents);
        return "xiangqin";
    }

    @RequestMapping("/buyOrder/{goodsid}")
    public String buyOrder(HttpServletRequest request,@PathVariable("goodsid") Integer goodsid,@RequestParam(defaultValue = "1") Integer count){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if(user==null){
            return "redirect:/preindex/onlygoods/"+goodsid;
        }
        Order order = new Order();
        order.setGoodsId(goodsid);

        order.setUserId(user.getId());
        order.setOrdertime(DateUtil.getDate());
        order.setNum(count);
        orderServer.buyOrder(order);
        return "redirect:/preindex/onlygoods/"+goodsid;
    }
}
